<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Queue;

use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkClickContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContactContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkStatisticContract;

/**
 * 引流链接
 * Class LinkClickStatisticQueue.
 */
class LinkClickStatisticQueue
{
    /**
     * @Inject
     * @var DrainageLinkClickContract
     */
    protected $drainageLinkClick;

    /**
     * @Inject
     * @var DrainageLinkContactContract
     */
    protected $drainageLinkContact;

    /**
     * @Inject
     * @var DrainageLinkStatisticContract
     */
    protected $drainageLinkStatistic;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @AsyncQueueMessage(pool="default")
     */
    public function handle()
    {
        $day = date('Y-m-d');
        if (! empty($this->drainageLinkStatistic->getDrainageLinkStatisticsByDay($day))) {
            return false;
        }
        $clickRecord = $this->drainageLinkClick->getDrainageLinkClicksByCreatedAt($day);
        $linkContact = $this->drainageLinkContact->getDrainageLinkContactByCreatedAt($day);
        $list = [];
        foreach ($linkContact as $LinkItem) {
            $list[$LinkItem['linkId']] = $LinkItem['total'];
        }
        foreach ($clickRecord as $item) {
            $statistics = [
                'link_id' => $item['linkId'],
                'created_at' => $day,
                'click_number' => $item['total'],
                'add_number' => 0,
                'add_rate' => 0,
            ];
            if (! empty($list[$item['linkId']])) {
                $statistics['add_number'] = $list[$item['linkId']];
                $statistics['add_rate'] = (number_format($list[$item['linkId']] / $item['total'], 2) * 100) . '%';
            }

            $statistic = $this->drainageLinkStatistic->getDrainageLinkStatisticByLinkIdDay((int) $item['linkId'], $day, ['id']);
            if (! empty($statistic)) {
                unset($statistics['link_id'], $statistics['created_at']);
                $this->drainageLinkStatistic->updateDrainageLinkStatisticById($statistic['id'], $statistics);
            } else {
                $this->drainageLinkStatistic->createDrainageLinkStatistic($statistics);
            }
        }
        return true;
    }
}
